import {GeneratedType, Registry} from "@cosmjs/proto-signing";

require("dotenv").config();
const { DirectSecp256k1HdWallet} = require("@cosmjs/proto-signing");

const { IndexedTx,SigningStargateClient, StargateClient } = require("@cosmjs/stargate")
const { stringToPath } = require("@cosmjs/crypto")

const { MsgSend } = require("cosmjs-types/cosmos/bank/v1beta1/tx");
const { Tx } = require("cosmjs-types/cosmos/tx/v1beta1/tx");

const { MsgReceiveMessage } = require("../generated/circle/cctp/v1/tx")
//const { MsgReceiveMessage } = require('./message');
const config = require('../config');

const rpc = config.noble.url;


const { ethers } = require('ethers');
const attestationApi = config.attestationApi.url;
const axios = require('axios');

const Web3 = require('web3');

let txHash = "0x43f17e86f1932de6491b1465bb561150e3a62bef8c9261e6c3622a3e99efd70c";

let url = config.goerli.urls[1];


export const cctpTypes: ReadonlyArray<[string, GeneratedType]> = [
    ["/circle.cctp.v1.MsgReceiveMessage", MsgReceiveMessage],
];

function createDefaultRegistry(): Registry {
    return new Registry(cctpTypes)
}


const mint = async (message, attestation)=>{
    console.log('config.mnemonic: ', config.MNEMONIC);

    const mnemonic = config.MNEMONIC;
    const wallet = await DirectSecp256k1HdWallet.fromMnemonic(
        mnemonic,
        {
            hdPaths: [stringToPath("m/44'/118'/0'/0/0")],
            prefix: "noble"
        }
    );

    const [account] = await wallet.getAccounts();

    console.log(account.address)

    const client = await SigningStargateClient.connectWithSigner(rpc, wallet, {registry: createDefaultRegistry()});

    //console.log("message: ", message)
    //console.log("attestation: ", attestation)

    let receiveMsg = {
        version:0,
        destinationDomain:4,
        nonce:1,
        recipient:account.address,
        messageBody:message
    }

    const receiveMsgBuf = Buffer.from(JSON.stringify(receiveMsg))
    const receiveMsgBytes = new Uint8Array(receiveMsgBuf);

    const msg = {
        typeUrl:"/circle.cctp.v1.MsgReceiveMessage",
        value:{
            from:account.address,
            message:message,
            attestation:attestation,
        }
    }
    const fee = {
        amount: [
            {
                denom: "uusdc",
                amount: "200000",
            },
        ],
        gas: "200000",
    };
    const memo = "haolf";
    const result = await client.signAndBroadcast(
        account.address,
        [msg],
        fee,
        memo
    );
    console.log("result: ", result)
}

function hexToBytes(hex) {
    let bytes = [];
    for (let c = 0; c < hex.length; c += 2)
        bytes.push(parseInt(hex.substr(c, 2), 16));
    return bytes;
}

const run = async ()=>{
    let web3 = new Web3(new Web3.providers.HttpProvider(url));
    const eventTopic = web3.utils.keccak256('MessageSent(bytes)');

    const transactionReceipt = await web3.eth.getTransactionReceipt(txHash);
    const log = transactionReceipt.logs.find((l) => l.topics[0] === eventTopic)
    console.log("log : ", log);
    const messageBytes = web3.eth.abi.decodeParameters(['bytes'], log.data)[0]
    console.log("messageBytes: ", messageBytes);
    const messageHash = web3.utils.keccak256(messageBytes);


    console.log('messageHash: ', messageHash);
    //const res = await axios.get(attestationApi + messageHash);
    //console.log('res.data, ', res.data);

    //let attestation = res.data.attestation;
    
    let attestation = 'af16f1c051310000d6b0204558d026e58ac5dbe607faed2723a1a3378859046d20367faeba595ffb371567fda922a6d0e5c938555e9a1cec0261f8d63ce126261b9799b96c0abb2627b8090b2f455e318530bd496b58cb36c47a46f0f512663cad71a47bd25614e2d947c65d3259201ca47e85164fce0a421f47e01bcbda3c4a191c'
    let message = messageBytes.slice(2);
    message = "000000000000000000000004000000000003ace2000000000000000000000000d0c3da58f55358142b8d3e06c1c30c5c6114efe800000000000000000000000057d4eaf1091577a6b7d121202afbd2808134f11700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007865c6e87b9f70255377e024ace6630c1eaa37f0000000000000000000000006a769dbfb6a90de5671102d35285a412d0f963e80000000000000000000000000000000000000000000000000000000000000001000000000000000000000000ef48c3ab7f184e469504bdbd9c07883ab4427c66"

    

    console.log('attestation: ', attestation)
    console.log('message: ', message)

    const attest_buffer = Buffer.from(attestation, "hex")
    const message_buffer = Buffer.from(message, "hex")

    //const attest_bytes = hexToBytes(attestation);
    console.log("attest_bytes: ", attest_buffer.length)
    //const message_bytes = hexToBytes(message);

    await mint(message_buffer, attest_buffer)
}

run();
